var events = require('events');
var util = require('util');
var uuid = require('uuid');
var ElasticSearchClient = require('elasticsearchclient');
var config = require('./config');
var mailUtil = require('./mailUtil');

var serverOptions = {
	host : config.elServerHost,
	port : config.elServerPort
};
var searchClient = new ElasticSearchClient(serverOptions);

var mailFolders = [ 'OpenProject' ];

mailFolders.forEach(function(folder) {
	var emailReceiver = new mailUtil.EmailReceiver(config);
	emailReceiver.readAllEmails(folder, function(error, result) {
		if (error) {
			console.log(error);
		} else {
			var document = {};
			document.id = uuid.v1();
			document.content = result.content;
			document.from = result.head.from;
			document.receivers = result.head.to;
			document.subject = result.head.subject;
			var date = new Date(result.head.date);
			document.sendDate = date.toISOString();
			searchClient.index('email', '163', document, document.id, null)
			.on(
				'data',
				function(data) {
					console.log('============EL index result: [%s]',
							document.subject);
			})
			.on('error', function(error) {
				console.log('============EL error: ' + error);
			}).exec();
		}
	});
});
